(function($){

    var dataService =function(service_url){
        var data_array = [];
        $.ajax({
            type: "GET",
            url: service_url,
            async:false,
            dataType: "json",
            success: function(data){

                $.each(data, function(index, obj){
                    data_array.push(obj);
                });
            },
            error:function(){
            }
        });
        return data_array;
    };

    $.vars = $.extend({}, $.vars);
    $.vars.citypicker = {
        pro : new Array(),
        cities : new Array(),
        districts : new Array()
    };

    //$.citypicker({defaultDistrict":"1001", callback_fun:function(){}, callback_params:{}});
    //$.citypicker("setDesc","1001");
    jQuery.fn.extend({
        "citypicker": function(options,_param){

            if($.vars.citypicker.url == undefined){
                globals = $.extend({}, globals);
                if(globals.citypicker == undefined || globals.citypicker == null){
                    alert("Error: No CityPicker setup!");
                    return this;
                }else{
                    $.vars.citypicker.url = {
                                province: globals.citypicker.host+"/ws/cityPicker/provinces",
                                city: globals.citypicker.host+"/ws/cityPicker/cities/",
                                district: globals.citypicker.host+"/ws/cityPicker/districts/",
                                description: globals.citypicker.host+"/ws/cityPicker/description/"
                            };
                }
            }

            function setDesc(districtVal,_element){
                $.ajax({
                    type: "GET",
                    url: $.vars.citypicker.url.description+districtVal,
                    async:false,
                    dataType: "json",
                    success: function(data){
                        var desc = data["nameDesc"];
                        if(desc!=null)
                            $(_element).val(desc);
                    },
                    error:function(){
                        alert("test");
                    }
                });
            }

            if($.vars.citypicker.pro.length==0){
                $.vars.citypicker.pro = dataService($.vars.citypicker.url.province);
            }

            if(options=="setDesc"){

                return this.each(function () {
                    if(_param!=undefined && _param!=null && _param!=""){
                        setDesc(_param,this);
                        $(this).trigger("callback",[_param]);
                    }
                })
            }

            options = $.extend({}, options);

            return this.each(function(){
                if(options.callback_fun){
                    $(this).bind("callback",options.callback_params,options.callback_fun);
                }
                if(options.defaultDistrict!=undefined
                    && options.defaultDistrict!=null
                    && options.defaultDistrict!=""){
                    setDesc(options.defaultDistrict,this);
                }
                new jQuery.CityPicker(this,options);
            });
        }
    });

    jQuery.CityPicker = function(obj,options){
        var $input = $(obj);
        //产生一个选择器
        var $container = setupContainer(options);
        
        $input.click(function(event){
            $(".citypicker_container").hide();
            //设置当前不可读
            this.readOnly = true;
            //得到输入框的位置
            var offset = $input.offset();
            //得到输入框的高度,宽度
            var height = $input.height();
            var width = $input.width();
            //计算选择器的位置
            var cont_top = offset.top + height;
            var cont_left = offset.left;
            //设置选择器出现的位置
            $container.appendTo($("body")).css({
                'top': cont_top + 5,
                'left': cont_left
            });
            if ($container.is(":hidden")) {
                //当前选择器是隐藏的
                $container.show();
            } else  if ($container.is(":visible")) {
                    //当前选择器是显示的
                    //停止事件冒泡
                    event.stopPropagation();
                }
            return false;
        });
        //点击在选择器以外，隐藏它
        $(document).bind("click", function(event){
            var $target = $(event.target);
			console.log();
			
            var hideFag = $target.parent("div").attr("id");
			if($target.parent("li").length == 0){
				if (!(hideFag == "citypicker_container" || hideFag == "citypicker_dis"|| hideFag == "citypicker_city" || hideFag == "citypicker_pro")) {
					$container.hide();
				}
			} 
						
        });
        
        //初始化选择器函数
        function setupContainer(options){
            var proCityDis = new Array();
            var $container = $("<div></div>").attr("id", "citypicker_container").addClass("citypicker_container");
            var $prov = $("<div></div>").attr("id", "citypicker_pro");
            var $city = $("<div></div>").attr("id", "citypicker_city").hide();
			var $district = $("<div></div>").attr("id","citypicker_dis").hide();
            $container.append('<ul><li><a href="#citypicker_pro">省份</a></li><li><a href="#citypicker_city">城市</a></li><li><a href="#citypicker_dis">区县</a></li></ul>').append($prov).append($city).append($district);
			var $containerTabs = $container.tabs();
			if (proCityDis.length > 0){
					for(t in proCityDis){
						if (t != 0 && proCityDis[t]=='') {
						$containerTabs.tabs(destroy);
						$containerTabs.tabs({disabled:[t]});
						} 
					}
				} else {
				 $containerTabs.tabs({disabled:[1,2]});
				}
            var pro = $.vars.citypicker.pro;
            for (p in pro) {
                $("<label>" + pro[p]['name'] + "</label>").attr("id","p-"+pro[p]['id']).appendTo($prov).click(function(){
                    var pId = "";
                    var i = $(this).text();
					proCityDis[0] = i;
                    //被点了的省份字体色改变
                    $(this).css({ 'color': 'blue'});
					$(this).siblings().css({'color': 'green'});
					$containerTabs.tabs( "enable", 1); 
					$containerTabs.tabs({selected: '1'});

                    var pid = $(this).attr("id").split("-")[1];

                    var cities = $.vars.citypicker.cities = dataService($.vars.citypicker.url.city+pid);

                    //清空城市，让另外一个省的城市显示在此处
                    $city.empty();
                    for (c in cities) {
                        $("<label>" + cities[c]["name"] + "</label>").attr("id","c-"+cities[c]['id']).appendTo($city).click(function(){
//                            //这里把相应的值设置到输入框当中去
                            var j = $(this).text();
						    proCityDis[1] = j;
							$containerTabs.tabs( "enable", 2);
						    $containerTabs.tabs({selected: '2'});
							$(this).css({
                                'color': 'blue'
                            });
							$(this).siblings().css({'color': 'green'});

                            var cid = $(this).attr("id").split("-")[1];

                            var districts = $.vars.citypicker.districts = dataService($.vars.citypicker.url.district+cid);

							$district.empty();
							for(d in districts){

								$("<label>"+districts[d]["name"]+"</label>").attr("id",districts[d]['id']).appendTo($district).click(function(){
//                                    areaIds = pid+"-"+cid+"-"+$(this).attr("id");
                                    $(obj).trigger("callback",[$(this).attr("id")]);
									$(this).css({
										'color': 'blue'
										});
									$(this).siblings().css({'color': 'green'});
									proCityDis[2] = $(this).text();
									$(obj).val(proCityDis[0]+'-'+proCityDis[1]+'-'+proCityDis[2]);
									//选择以后隐藏选择器
									$container.fadeOut("fast");
								});
							}
                        });
                    }
                });
            }
            return $container;
        }
    }
})(jQuery);
